package com.xgjweb.fsi.service;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xgjweb.common.dao.ICommonDao;
import com.xgjweb.common.service.CommonServiceImpl;
import com.xgjweb.common.utils.Constant;
import com.xgjweb.common.utils.XgjWebLogger;
import com.xgjweb.common.utils.XgjWebUtils;
import com.xgjweb.fsi.domain.Link;

public class LinkServiceImpl extends CommonServiceImpl implements ILinkService {
	private ICommonDao linkDao;

	public void setLinkDao(ICommonDao linkDao) {
		this.linkDao = linkDao;
	}

	/**
	 * 添加链接
	 */
	public ActionForward addLink(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		File imageFile = null;
		try {
			request.setCharacterEncoding("UTF-8");
			String path = Constant.LINK_PATH;
			RequestContext requestContext = new ServletRequestContext(request);
			// 得到参数
			String name = parmentByRequest(request, "name");
			name = ReEncode(name);
			// 用uuid生成文件名
			String image = XgjWebUtils.getUUID();
			String desc = parmentByRequest(request, "desc");
			Integer sort=Integer.parseInt(parmentByRequest(request, "sort"));
			desc = ReEncode(desc);
			String url = parmentByRequest(request, "url");
			url = ReEncode(url);
			if (FileUpload.isMultipartContent(requestContext)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置文件最大为1M
				upload.setSizeMax(1024 * 1024);
				List<?> items;
				items = upload.parseRequest(request);
				Iterator<?> it = items.iterator();
				while (it.hasNext()) {
					FileItem fileItem = (FileItem) it.next();
					if (!fileItem.isFormField()) {
						if (fileItem.getName() != null
								&& fileItem.getSize() != 0) {
							// 保存文件到硬盘
							image = image + "."
									+ fileItem.getName().split("\\.")[1];
							imageFile = new File(path + File.separator + image);
							// 保存图片到硬盘
							fileItem.write(imageFile);
							// 把link信息写进数据库
							Link link = new Link();
							link.setDesc(desc);
							link.setName(name);
							link.setImage(image);
							link.setUrl(url);
							link.setSort(sort);
							link.setStatementName("insertLink");
							linkDao.insert(link);
						}
					}

				}
			}
			return null;
		} catch (Exception e) {
			// 发生异常把保存的新图片删除。
			if (imageFile != null && imageFile.exists()) {
				imageFile.delete();
			}
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 删除链接
	 */
	public Boolean deleteLink(Link link) throws Exception {
		try {
			File file = new File(Constant.LINK_PATH + link.getImage());
			if (file.exists()) {
				file.delete();
			}
			link.setStatementName("deleteLink");
			linkDao.delete(link);
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查找链接
	 */
	public Link findLink(Link link) throws Exception {
		try {
			link.setStatementName("findLink");
			link = (Link) linkDao.selectByObject(link);
			return link;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查询链接
	 */
	@SuppressWarnings("unchecked")
	public List<Link> queryLink() throws Exception {
		try {
			Link link = new Link();
			link.setStatementName("queryLink");
			List<Link> links = linkDao.selectByList(link);
			return links;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 更新链接
	 */
	public Boolean updateLink(Link link) throws Exception {
		try {
			link.setStatementName("updateLink");
			linkDao.update(link);
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}
	/**
	 * 初始化Sort
	 */
	public Integer initSort() throws Exception {
		Link link = new Link();
		link.setStatementName("findMaxSort");
		return(Integer)linkDao.selectByObject(link);
	}

}
